<template>
  <div>
    <!--面包屑导航区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片视图区域-->
    <el-card>
      <!--添加分类按钮区域-->
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddDialog">添加分类</el-button>
        </el-col>
      </el-row>
      <!--表格区域-->
      <tree-table class="treeTable" :data="cateList" :columns="columns" :selection-type="false" :expand-type="false" show-index index-text="#" border :show-row-hover="false">
        <!--有效-->
        <template slot="isOk" slot-scope="scope">
          <i class="el-icon-success" v-if="scope.row.cat_deleted === false" style="color: lightgreen"></i>
          <i class="el-icon-error" v-else style="color:red"></i>
        </template>
        <!--排序-->
        <template slot="order" slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag size="mini" type="success" v-else-if="scope.row.cat_level === 1">二级</el-tag>
          <el-tag size="mini" type="warning" v-else>三级</el-tag>
        </template>
        <!--操作-->
        <template slot="opt" slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row)">编辑</el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeCateById(scope.row)">删除</el-button>
        </template>
      </tree-table>

      <!--添加分类的对话框-->
      <el-dialog title="添加分类" :visible.sync="addCateDialogVisible" width="50%" @close="addCateDialogClosed">
        <el-form :model="addCateForm" :rules="addCateFormRules" ref="addRef" label-width="100px">
          <el-form-item label="分类名称" prop="cat_name">
            <el-input v-model="addCateForm.cat_name"></el-input>
          </el-form-item>
          <el-form-item label="父级分类">
            <el-cascader
              v-model="selectedKeys"
              :options="parentCateList"
              :props="{ expandTrigger: 'hover', label: 'cat_name', value: 'cat_id', checkStrictly: true }"
              @change="parentCateChanged" clearable ></el-cascader>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addCateDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addCate">确 定</el-button>
        </span>
      </el-dialog>

      <!--编辑分类的对话框-->
      <el-dialog title="编辑分类" :visible.sync="editCateDialogVisible" width="50%" @close="editCateDialogClosed">
        <el-form :model="editCateForm" :rules="editCateFormRules" ref="editFormRef" label-width="100px">
          <el-form-item label="分类名称" prop="cat_name">
            <el-input v-model="editCateForm.cat_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editCateDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editCate">确 定</el-button>
        </span>
      </el-dialog>

      <!--分页区域-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="this.queryInfo.pagenum"
        :page-sizes="[1, 5, 10, 20]"
        :page-size="this.queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="this.total">
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'Cate',
  data() {
    return {
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 10
      },
      // 商品分类的数据列表, 默认为空
      cateList: [],
      // 总数据条数
      total: 0,
      // 为table指定列的定义
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name'
        },
        {
          label: '是否有效',
          type: 'template',
          template: 'isOk'
        },
        {
          label: '排序',
          type: 'template',
          template: 'order'
        },
        {
          label: '操作',
          type: 'template',
          template: 'opt'
        }
      ],
      // 控制添加分类对话框的显示与隐藏
      addCateDialogVisible: false,
      // 添加分类的表单数据对象
      addCateForm: {
        cat_name: '',
        cat_pid: 0,
        // 默认一级分类
        cat_level: 0
      },
      // 添加分类表单的验证规则对象
      addCateFormRules: {
        cat_name: [
          { required:true, message: '请输入分类名称', trigger: 'blur'}
        ]
      },
      // 父级分类列表数据
      parentCateList: [],
      // 选中的父级分类的id数组
      selectedKeys: [],
      // 控制编辑分类对话框的显示与隐藏
      editCateDialogVisible: false,
      // 编辑分类id
      editId: '',
      // 编辑分类的表单数据对象
      editCateForm: {
        cat_name: ''
      },
      // 编辑分类表单的验证规则对象
      editCateFormRules: {
        cat_name: [
          { required:true, message: '请输入分类名称', trigger: 'blur'}
        ]
      },
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 获取商品分类数据
    async getCateList() {
      let {data: res} = await this.$http.get('categories', { params: this.queryInfo })
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类失败!')
      }
      // 保存数据
      this.cateList = res.data.result
      this.total = res.data.total
    },
    // pageSize 改变时会触发
    handleSizeChange(pagesize) {
      this.queryInfo.pagesize = pagesize
      this.getUserList()
    },
    // currentPage 改变时会触发
    handleCurrentChange(pagenum) {
      this.queryInfo.pagenum = pagenum
      this.getUserList()
    },

    // 显示添加分类对话框
    showAddDialog() {
      this.addCateDialogVisible = true
      this.getParentCateList()
    },
    async getParentCateList() {
      let {data: res} = await this.$http.get('categories', {
        params: { type: 2 }
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类失败!')
      }
      // 保存数据
      this.parentCateList = res.data
    },
    // 选择项发生变化时触发这个函数
    parentCateChanged() {
      console.dir(this.selectedKeys)
      // 如果 selectedKeys 数组中的 length 大于0 , 证明选中了父级分类
      if (this.selectedKeys.length === 0) return

      // 保存数据
      this.addCateForm.cat_pid = this.selectedKeys[this.selectedKeys.length - 1]
      this.addCateForm.cat_level = this.selectedKeys.length
    },
    // 监听添加分类对话框的关闭事件
    addCateDialogClosed() {
      // 清空数据
      this.$refs.addRef.resetFields()
      this.selectedKeys = []
      this.addCateForm.cat_level = 0
      this.addCateForm.cat_pid = 0

      this.addCateDialogVisible = false
    },
    // 点击确定, 添加分类
    addCate() {
      this.$refs.addRef.validate(async valid => {
        if (!valid) return

        let {data: res} = await this.$http.post('categories', this.addCateForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加分类失败')
        }
        this.$message.success('添加分类成功')

        this.getCateList()
        this.addCateDialogClosed()
      })
    },
    // 显示编辑分类对话框
    showEditDialog(row) {
      // 填充数据
      this.editId = row.cat_id
      this.editCateForm.cat_name = row.cat_name
      this.editCateDialogVisible = true
    },
    // 关闭编辑分类对话框
    editCateDialogClosed() {
      // 清空编辑数据
      this.editCateForm = {}

      this.editCateDialogVisible = false
    },
    // 编辑分类
    editCate() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return

        let {data: res} = await this.$http.put('categories/' + this.editId, this.editCateForm)
        if (res.meta.status !== 200) {
          return this.$message.error('编辑分类失败')
        }
        this.$message.success('编辑分类成功')

        this.getCateList()
        this.editCateDialogClosed()
      })
    },
    // 根据id删除对应的分类
    async removeCateById(row) {
      // 弹框询问是否删除
      let confirmResult = await this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }

      let {data: res} = await this.$http.delete(`categories/${row.cat_id}`)

      if ( res.meta.status !== 200 ){
        return this.$message.error(res.meta.msg)
      }

      this.$message.success('删除成功')
      this.getCateList()
    },
  }
}
</script>

<style scoped>

.treeTable{
  margin-top: 15px;
}

.el_cascader{
  width: 100%;
}
</style>
